package o2o.config.jms.listener;

import com.alibaba.fastjson.JSON;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.config.jms.convert.NotifyMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: Jahnke [1029777564@qq.com]
 * Date: 2018-05-04 17:58
 * To change this template use File | Settings | File Templates.
 */
@Component
public class TopicMessageListener implements MessageListener {

    private static Logger logger = LoggerFactory.getLogger(TopicMessageListener.class);
    private ExecutorService pool = Executors.newFixedThreadPool(30);

    @Autowired
    private NotifyMessageConverter messageConverter;

    /**
     * 接收消息
     */
    public void onMessage(Message message) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    JMSNotify notify = (JMSNotify) messageConverter.fromMessage((ObjectMessage) message);
                    if (notify != null) {
                        //处理接受到的数据
                        System.out.println("接受到的同步数据:" + JSON.toJSONString(notify));
                    }
                } catch (Exception e) {
                    logger.error("从消息队列获得上行信息异常{}", e);
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

    }

}
